package com.hongdee.crm.approval.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.approval.dao.ITCrmCarApprovalFlowDetailDao;
import com.hongdee.crm.approval.entity.TCrmCarApprovalFlowDetail;
import com.hongdee.crm.approval.service.ITCrmCarApprovalFlowDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/8/3.
 */
@Service
public class TCrmCarApprovalFlowDetailServiceImpl implements ITCrmCarApprovalFlowDetailService {
    @Autowired
    private ITCrmCarApprovalFlowDetailDao itCrmCarApprovalFlowDetailDao;

    /**
     * 新增审批明细
     * @param data
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public TCrmCarApprovalFlowDetail save(TCrmCarApprovalFlowDetail data,String uid) throws Exception{
        if (data.getId() == null) {
            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());

        } else {
            throw new Exception("不允许修改审批明细！");
        }
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        data.setApprovalDate(format.format(date));
        data.setCompanyId(TokenUtil.getCompanyId(uid));
        data.setApprovaler(uid);
        this.itCrmCarApprovalFlowDetailDao.saveOrUpdate(data);
        return data;
    }
    /**
     * 审批明细分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map approvalPage(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select p.*,tbu.u_name approvalers from T_CRM_CAR_APPROVALFLOW_DETAIL p left join " +
                " t_bc_user tbu on tbu.id = p.approvaler where p.company_id = ?");
        params.add(TokenUtil.getCompanyId(uid));
        if(data.get("id")!=null&&!StringUtils.isEmpty(data.get("id"))){
            sql.append(" and bill_id = ? ");
            params.add(data.get("id"));
        }
        if(data.get("type")!=null&&!StringUtils.isEmpty(data.get("type"))){
            sql.append(" and bill_type = ? ");
            params.add(data.get("type"));
        }
        return this.itCrmCarApprovalFlowDetailDao.page(sql.toString(), params.toArray(), start, limit);
    }

}
